const express = require("express")
const router = express.Router()
const { query } = require("../db/index")
const { setToken } = require("../utils/index")
const bcrypt = require("bcryptjs")
const { schemaLogin } = require("../schema/login")
const validate = require("../schema/index")

/* GET home page. */
router.post("/login", validate.body(schemaLogin), async function (req, res) {
  //  await query()
  try {
    const sql = "select * from t_user where username = ? "

    const result = await query(sql, req.body.username)
    if (result.length !== 1) return res.sendError("用户名不存在")
    const pwdIsReady = bcrypt.compareSync(req.body.password, result[0].password)
    if (pwdIsReady) {
      return res.sendSuccess({
        token: setToken({ ...result[0], password: "" })
      })
    }
    return res.sendError("用户名或密码不正确")
  } catch (error) {
    return res.sendError(error.message)
  }
})

module.exports = router
